﻿using System.Web.Mvc;

namespace Songhay.Web.Mvc.ActionResults
{
    /// <summary>
    /// Returns an XML string as <c>"text/html"</c> or <c>"text/xml"</c>.
    /// </summary>
    public class XmlStringResult : ActionResult
    {
        /// <summary>
        /// Constructs from the specified XML <see cref="System.String"/>.
        /// </summary>
        /// <param name="xmlString">The specified XML <see cref="System.String"/></param>
        public XmlStringResult(string xmlString)
        {
            this._xmlString = xmlString;
        }

        /// <summary>
        /// Constructs from the specified XML <see cref="System.String"/>
        /// and emit XHTML flag.
        /// </summary>
        /// <param name="xmlString">The specified XML <see cref="System.String"/></param>
        /// <param name="emitXhtml">When <c>true</c>, set the Response Content Type to <c>"text/html"</c></param>
        public XmlStringResult(string xmlString, bool emitXhtml)
        {
            this._emitXhtml = emitXhtml;
            this._xmlString = xmlString;
        }

        /// <summary>
        /// Implements <see cref="System.Web.Mvc.ActionResult.ExecuteResult"/>
        /// </summary>
        /// <param name="context">The <see cref="ControllerContext"/></param>
        public override void ExecuteResult(System.Web.Mvc.ControllerContext context)
        {
            if(this._xmlString != null)
            {
                context.HttpContext.Response.Clear();
                context.HttpContext.Response.ContentType = (this._emitXhtml) ? "text/html" : "text/xml";
                context.HttpContext.Response.Write(this._xmlString);
            }
        }

        private bool _emitXhtml = false;
        private string _xmlString = null;
    }
}
